<template>
  <div>
    <newHeader></newHeader>
    <swiperComponent></swiperComponent>
    <div class="m-content wrapbox clearfix">
      <div class="m-leftbar">

        <div class="m-arrdet">
          <div class="box">
            <span class="n">{{name}}</span>
            <!--<span class="t">对标签的解释文案对标签的解释文案对标签的解释文案</span>-->
          </div>
          <div style="float:left;margin-left: 50px;color: #337ab7;font-size: 18px;">
            <a @click="followPlat">{{followText}}</a>
          </div>
        </div>

        <div class="m-hotnav" v-show="!isLogin">
          <h2 class="sider-title">币推荐</h2>
        </div>

        <div class="articles" v-if="articles && articles.length">
          <ul>
            <li class="article-item" v-for="(article, index) in articles" :key="index">
              <article-block
                :article="article"
                :tags="article.tags || []"
                :comments="article.comments || []"
                @load-comments="loadMoreComment(article)"
                @share="onShare(article)"
                @like="onLike"
                @post-comment="onPostComment"
                @like-comment="onLikeComment"
                @report-comment="onReportComment"
                @delete-comment="onDeleteComment"
                @post-comment-reply="onPostCommentReply"
                @report-reply="onReportReply"
                @post-reply-reply=""
                @delete-reply="onDeleteReply">
              </article-block>
            </li>
          </ul>
        </div>
        <vue-paginate-al :nextText="paginate.nextText" :prevText="paginate.prevText" :totalPage="totalPage"
                         :currentPage="currentPage" @btnClick="getNews"></vue-paginate-al>
      </div>
      <div class="m-rightbar">
        <!-- S 侧边栏 -->

        <div class="m-hotarr">
          <div class="hd">
            <h2 class="sider-title">热门标签</h2>
          </div>
          <div class="bd">
            <ul class="list clearfix">
              <li v-for="plat in hotPlate">
                <router-link v-bind="{to:'/platDetail/'+ plat.id+'/'+plat.name}">{{plat.name}}</router-link>
              </li>
            </ul>
          </div>
        </div>
        m
        <div class="m-rank">
          <div class="hd">
            <h2 class="sider-title">达人榜</h2>
            <router-link class="more" v-bind="{to:'/Master/'+userId}">更多</router-link>
          </div>
          <div class="bd">
            <ul class="list">
              <li v-for="item in MasterList">
                <div class="m">
                  <span class="pic"> <router-link v-bind="{to:'/MySlef/'+ item.userId}">
                    <img v-show="item.picUrl!=null" :src="item.picUrl" width="40" height="40"/>
                    <img v-show="item.picUrl==null" src="../images/img01.png" width="40" height="40"/></router-link>
                  </span>
                  <div class="master">
                    <p class="name">{{item.nickname==null?"未知用户":item.nickname}}</p>
                    <p class="time">{{item.fans}} 粉丝</p>
                  </div>
                  <a v-show="!item.hasFlow" class="addfocus" @click='isFocus(item)'>+ 关注</a>
                  <a v-show="item.hasFlow" class="addfocus" @click='isFocus(item)'>取消关注</a>
                </div>
                <p class="txt">{{item.profile}}</p>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
    <bottom></bottom>
  </div>
</template>

<script>
  import newHeader from '@/components/NewHeader';
  import bottom from '@/components/Bottom';
  import swiperComponent from '@/components/SSwiper';
  import articleBlock from '@/components/article-block/index';
  import {mapGetters} from 'vuex'
  import VuePaginateAl from 'vue-paginate-al'

  let STATUS = {
    notStart: '',
    doing: 'doing',
    done: 'done',
    fail: 'fail'
  };

  export default {
    components: {
      bottom,
      newHeader,
      swiperComponent,
      articleBlock,
      VuePaginateAl,
    },
    data() {
      return {
        hotPlate: [],
        tab: -1,
        followText: '关注',
        articles: null,
        name: '',
        platId: 0,
        currentPage: 1,
        totalPage: 0,
        paginate: {
          nextText: '下一页',
          prevText: '上一页',

        },
        MasterList: [],
      };
    },
    mounted() {
      this.name = this.$route.params.name
      this.platId = this.$route.params.id
      this.getNewsList()
      this.getMasterList()
      this.$store.dispatch('updateHeadStatu', true)
      this.queryPlateList()
    },

    computed: {
      ...mapGetters({
        userId: 'userId',
        isLogin: 'isLogin',
        username: 'username',
        photo: 'photo',
      })
    },
    methods: {
      followPlat() {
        let opt = 1
        if (this.followText == '关注') {
          opt = 1
        } else {
          opt = 2
        }

        let params = {
          "optType": opt,
          "type": 2,
          "value": this.platId
        }
        this.$post('/userRef/saveUserRef', params).then(response => {
          this.$check(response)
          if (opt == 1) {
            this.followText == '已关注'
          } else {
            this.followText == '关注'
          }

        })
      },
      isFocus(item) {
        let opt = 0
        if (item.hasFlow) {
          opt = 2
        } else {
          opt = 1
        }
        let params = {
          "optType": opt,
          "type": 1,
          "value": item.userId
        }
        this.$post('/userRef/saveUserRef', params).then(response => {
          this.$check(response)
          item.hasFlow = !item.hasFlow
        })
      },
      getArtical(type) {
        this.tab = type
        this.currentPage = 1
        this.getNewsList()
      },
      getMasterList() {
        let params = {
          "condition": {'userId': this.userId},
          "current": 0,
          "pages": 0,
          "size": 10,
          "total": 0,
        }
        this.$post('/user/getMasterList', params).then(response => {
          this.$check(response)
          this.MasterList = response.data.records
        })
      },
      getMysel(index) {
        this.$fetch('/user/getBaseUserInfo' + '?userId=' + index).then(response => {
          this.$check(response)
          this.mysle = response.data
        })
      },
      queryPlateList() {
        let params = {
          "condition": {},
          "current": 1,
          "pages": 0,
          "size": 100,
          "total": 0
        }
        this.$post('/plate/queryPlateList', params).then(response => {
          this.$check(response)
          this.hotPlate = response.data.records
        })
      },
      getNews(n) {
        this.currentPage = n
        this.getNewsList()

      },

      onShare(article) {
        // this.$post('/indexNews/addNewsReadings', {
        //   "newsId": article.id
        // }).then(response => {
        //   this.$check(response)
        article.shareCount += 1;
        // })
      },
      onLike(article, status) {
        article.likeActionStatus = STATUS.doing;
        // TODO send like request
        for (let item of this.articles) {
          if (item.id === article.id) {
            let likeInd = 1
            if (item.likeDone) {
              likeInd = 3
            } else {
              likeInd = 1
            }
            this.$post('/content/addContentLikesOrDislikes', {
              'id': article.id,
              'likeInd': likeInd,
              'type': 1
            }).then(response => {
              this.$check(response)
              item.likeDone = !article.likeDone;
              if (item.likeDone) {
                item.likeCount += 1;
              } else {
                item.likeCount -= 1;
              }
              this.$message.success('操作成功');
              item.likeActionStatus = STATUS.done;

            })
            break;
          }
        }
      },
      onLikeComment(comment, status) {
        comment.likeActionStatus = STATUS.doing;
        let likeInd = 1
        if (comment.likeDone) {
          likeInd = 3
        } else {
          likeInd = 1
        }
        this.$post('/content/addContentLikesOrDislikes', {
          'id': comment.id,
          'likeInd': likeInd,
          'type': 2
        }).then(response => {
          this.$check(response)
          comment.likeDone = !comment.likeDone;
          if (comment.likeDone) {
            comment.likeCount += 1;
          } else {
            comment.likeCount -= 1;
          }
          this.$message.success('操作成功');
          comment.likeActionStatus = STATUS.done;
        })

      },
      //提交评论
      onPostComment(article, comment) {
        article.postActionStatus = STATUS.doing;
        let params = {
          'conId': article.id,
          'content': comment,
          'parentId': 0,
        }
        this.$post('/content/addContentComment', params).then(response => {
          this.$check(response)
          article.comments.unshift({
            user: {
              avatar: this.photo,
              nickname: this.username
            },
            id: response.data,
            text: comment,
            likeDone: false,
            likeCount: 0,
            likeActionStatus: '',
            postActionStatus: '',
            reportActionStatus: '',
            deleteActionStatus: '',
            canDelete: true,
            replies: []
          });
          article.messageCount += 1;
          article.postActionStatus = STATUS.done;
        })
      },
      onReportComment(comment, reportArgs, article) {
        comment.reportActionStatus = STATUS.doing
        this.$post('/content/addContentCommentTips', {
          'conId': article.id,
          'commentId': comment.id,
          'content': reportArgs.text,
          'type': reportArgs.value,
          'userId': this.userId,
        }).then(response => {
          this.$check(response)
          this.$message.success('举报成功');
          comment.reportActionStatus = STATUS.done
        })
      },
      onDeleteComment(article, comment) {
        let commentFound = false;
        let count = 0;
        for (let item of article.comments) {
          if (item.id === comment.id) {
            commentFound = true;
            break;
          }
          count += 1;
        }
        if (commentFound) {

          this.$post('/content/delContentComment', {
            conId: article.id,
            commentId: comment.id
          }).then(response => {
            this.$check(response)
            this.$message.success('删除评论成功');
            article.messageCount -= (1 + comment.replies.length);
            article.comments.splice(count, 1);
          })
        }
      },
      onPostCommentReply(article, comment, reply) {
        comment.postActionStatus = STATUS.doing;
        let params = {
          'conId': article.id,
          'content': reply,
          'parentId': comment.id,
        }
        this.$post('/content/addContentComment', params).then(response => {
          this.$check(response)
          comment.replies.unshift({
            user: {
              avatar: this.photo,
              nickname: this.username
            },
            id: response.data,
            text: reply,
            likeDone: false,
            likeCount: 0,
            likeActionStatus: '',
            postActionStatus: '',
            reportActionStatus: '',
            deleteActionStatus: '',
            canDelete: true,
            replies: []
          });
          comment.postActionStatus = STATUS.done;
          article.messageCount += 1;
        })
      },
      onReportReply(reply, reportArgs, article) {
        reply.reportActionStatus = STATUS.doing
        this.$post('/content/addContentCommentTips', {
          'conId': article.id,
          'commentId': reply.id,
          'content': reportArgs.text,
          'type': reportArgs.value,
          'userId': this.userId,
        }).then(response => {
          this.$check(response)
          this.$message.success('举报成功');
          reply.reportActionStatus = STATUS.done
        })
      },
      onDeleteReply(article, comment, reply) {
        let replyFound = false;
        let count = 0;
        for (let item of comment.replies) {
          if (item.id === reply.id) {
            replyFound = true;
            break;
          }
          count += 1;
        }
        if (replyFound) {
          this.$post('/content/delContentComment', {
            conId: article.id,
            commentId: reply.id
          }).then(response => {
            this.$check(response)
            this.$message.success('删除评论成功');
            article.messageCount -= 1;
            comment.replies.splice(count, 1);
          })
        }
      },
      loadMoreComment(article) {
        let uuid = this.userId
        article.loadActionStatus = STATUS.doing;
        this.$post('/content/queryContentCommentList', {
          condition: {
            'conId': article.id,
            'userId': uuid,
          },
          current: article.nextCommentPage,
          size: 5
        }).then(response => {
          this.$check(response)
          if (response.data != null) {
            let records = response.data.records

            for (var i = 0; i < records.length; i++) {

              let subComments = this.getComment(records[i].children, uuid)
              article.comments.push({
                user: {
                  avatar: records[i].businessData.photo,
                  nickname: records[i].businessData.nickName,
                },
                id: records[i].businessData.id,
                text: records[i].businessData.contentStr,
                likeDone: records[i].businessData.likeInd == 1,
                likeCount: records[i].businessData.likes,
                likeActionStatus: '',
                postActionStatus: '',
                reportActionStatus: '',
                deleteActionStatus: '',
                canDelete: records[i].businessData.userId = uuid,
                replies: subComments
              })
            }
            if (response.data.records.length == 5) {
              article.nextCommentPage += 1;
            } else {
              article.nextCommentPage = 0;
            }
          } else {
            article.nextCommentPage = 0;
          }
          article.loadActionStatus = STATUS.done;
        })
      }, getComment(records, uuid) {
        let list = []
        for (var i = 0; i < records.length; i++) {
          list.push({
            user: {
              avatar: records[i].businessData.photo,
              nickname: records[i].businessData.nickName,
            },
            id: records[i].businessData.id,
            text: records[i].businessData.contentStr,
            likeDone: records[i].businessData.likeInd == 1,
            likeCount: records[i].businessData.likes,
            likeActionStatus: '',
            postActionStatus: '',
            reportActionStatus: '',
            deleteActionStatus: '',
            canDelete: records[i].businessData.userId = uuid,
            replies: []
          })
        }
        return list
      },
      getNewsList() {
        let params = {
          'condition': {
            'plateId': this.platId,
          },
          'current': this.currentPage,
          'pages': this.totalPage,
          'size': 10,
          'total': 0
        }
        this.$post('/content/queryHotPlateContentList', params).then(response => {
          this.$check(response)
          this.processList(response.data)
          this.articles = this.transfer(response.data.records)
          this.currentPage = response.data.current
          this.totalPage = response.data.pages
        })

      },
      processList(data) {
        if (data != null && data.records != null) {
          data.records.forEach(function (v) {
            if (v.plates != null && v.plates != '') {
              var tagList = []
              var tags = v.plates.split(',')
              tags.forEach(function (n) {
                var tt = n.split(':')
                if (tt.length == 2) {
                  var tag = {
                    'id': tt[0],
                    'name': tt[1]
                  }
                  tagList.push(tag)
                }
              }, this)
              v.tags = tagList
            }
          }, this)
        }
        return data
      },
      transfer(records) {
        let url = this.websideUrl
        records.forEach(function (v) {
          v.time = v.infopubldate
          v.text = v.contentAbstract
          // v.tags = v.tagList
          v.likeDone = v.likeInd == 1
          v.likeCount = v.likes
          v.messageCount = v.comments
          v.shareCount = v.shares
          v.comments = []
          v.likeActionStatus = ''
          v.postActionStatus = ''
          v.loadActionStatus = ''
          v.shareUrl = url + 'circleDetail/' + v.id
          v.routerUrl = '/circleDetail/' + v.id
          v.nextCommentPage = 1
        })
        return records

      },

    },
  };
</script>

<style scoped>
  .article-item {
    padding-bottom: 30px;
    border-bottom: 1px solid #ccc;
    margin-bottom: 15px;
  }

  .selectTag {
    background: #59B3E2;
    color: #fff;
  }

  .article-item:last-child {
    border-bottom: 0 none;
  }
</style>
